package io.alexkozlov.jpointfeddiscovery.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.alexkozlov.jpointfeddiscovery.StorageController;
import io.alexkozlov.jpointfeddiscovery.models.ServiceExport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

@RestController
@RequestMapping(path = "/services", produces="application/json")
public class WebController {

    @Autowired
    private StorageController storageController;

    // GET запрос
    @GetMapping("/get/{name}")
    public ArrayList<ServiceExport> get(@PathVariable String name) {
        return storageController.getExport(name);
    }

    @GetMapping("/")
    public ArrayList<ServiceExport> list() {
        return storageController.getExports();
    }

    // POST запрос
    @PostMapping("/add")
    public String add(@RequestBody String requestBody) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        ServiceExport serviceExport = objectMapper.readValue(requestBody, ServiceExport.class);
        boolean result = storageController.addExport(serviceExport);
        if (result) {
            return "{'status': 'ok','message': 'Сервис добавлен'}";
        } else {
            return "{status: 'error', message: 'Сервис не добавлен'}";
        }
    }

    @PostMapping("/remove")
    public String remove(@RequestBody String requestBody) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        ServiceExport serviceExport = objectMapper.readValue(requestBody, ServiceExport.class);
        var result = storageController.removeExport(serviceExport);
        if (result) {
            return "{'status': 'ok','message': 'Сервис удален'}";
        } else {
            return "{status: 'error', message: 'Сервис не удален'}";
        }
    }
}
